#include <pthread.h>
#include <stdio.h>

/*
从内存读变量值到寄存器

寄存器的值加1

将寄存器的值写回内存
*/

int a100 = 0;
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;

void* add_100(void* ptr)
{
    int i;
    for (i = 0; i < 100; i++)
    {
        //a100++;
        //但实际运行程序时很难观察到，为了使现象更容易观察到，我们把上述三条指令做的事情用更多条指令来做：
        pthread_mutex_lock(&counter_mutex);
        int val = a100;
        printf("%x: %d\n", (unsigned int)pthread_self(), val + 1);
        a100 = val + 1;
        pthread_mutex_unlock(&counter_mutex);
    }
}

int main()
{
    pthread_t pid[2];
    int i, j=500;
    void * tret;
    int old = 0;

    while ( j-- )
    {
        for (i = 0; i < 2; i++)pthread_create(&pid[i], NULL, add_100, NULL);
        for (i = 0; i < 2; i++)pthread_join(pid[i], &tret);
        printf("%d, 差%d\n", a100, a100-old);
        old = a100;
        sleep (1);
    }
    return 0;
}
